'use strict';

module.exports = (option, app) => {
  return async function(ctx, next) {
    if (app.config.authWhiteList.indexOf(ctx.url) !== -1) {
      await next(option);
      return;
    }
    const userId = ctx.request.headers['user-id'];
    const token = await app.redis.get(userId);
    if (token) {
      try {
        ctx.jwt().verify(token, app.config.jwtSecret);
      } catch (error) {
        ctx.returnBody({
          code: 401,
          message: '您未登录，请登录后再试',
        });
        return;
      }
      await next(option);
    } else {
      ctx.returnBody({
        code: 401,
        message: '您未登录，请登录后再试',
      });
      return;
    }
  };
};
